const path = require("path");

const webpack = require("webpack");

const { VueLoaderPlugin } = require("vue-loader");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: {
    app: "./src/main.js",
  },

  output: {
    filename: "js/[name].[hash:8].js",
    path: path.resolve(__dirname, "dist"),
    chunkFilename: "js/[id].[contenthash:8].js",
  },

  module: {
    rules: [
      // 加载 vue
      {
        test: /\.vue$/,
        use: "vue-loader",
      },
      // 加载 less css
      {
        test: /\.(less|css)$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: "../",
              // 开发环境开启热重载
              // hmr: process.env.NODE_ENV === "development",
            },
          },
          "css-loader",
          "less-loader",
        ],
      },
      // 加载 js
      {
        test: /\.js$/,
        exclude: /node_module/,
        use: [
          {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env"],
            },
          },
          {
            loader: "eslint-loader",
            options: {
              // 发生错误时终止打包
              failOnError: true,
            },
          },
        ],
      },
      // 加载 images
      {
        test: /\.(png|jpe?g|gif|svg)$/i,
        use: {
          loader: "file-loader",
          options: {
            esModule: false,
            outputPath: "images/",
          },
        },
      },
      // 加载 fonts
      {
        test: /\.(ttf|woff|woff2|eot|otf)$/,
        use: {
          loader: "file-loader",
          options: {
            esModule: false,
            outputPath: "fonts/",
          },
        },
      },
    ],
  },

  plugins: [
    // 加载 vue 单文件所需
    new VueLoaderPlugin(),

    // 创建 index.html，自动引入模块
    new HtmlWebpackPlugin({
      title: "My App",
      template: "./public/index.html",
    }),

    // 定义全局变量
    new webpack.DefinePlugin({
      BASE_URL: JSON.stringify(""),
    }),

    new MiniCssExtractPlugin({
      filename: "css/[name].[contenthash:8].css",
      chunkFilename: "css/[id].[contenthash:8].css",
    }),
  ],
};
